import os
from typing import Generator, Iterable
from pathspec import PathSpec
from pathspec.patterns.gitwildmatch import GitWildMatchPattern, GitWildMatchPatternError


def pjoin(*args):
    return os.path.join(*args)


def abspath(p: str):
    return os.path.abspath(p)


def basename(p: str):
    return os.path.basename(p)


def dirname(p: str):
    return os.path.dirname(p)


def remove_gitignore(
    gitignore_file: str,
    paths_to_check: Iterable[str],
) -> Generator[str, None, None]:
    """
    解析 .gitignore 文件，并返回paths_to_check中不被 .gitignore 匹配上的路径
    """
    with open(gitignore_file, "r", errors="ignore") as gitignore_file:
        try:
            spec = PathSpec.from_lines(GitWildMatchPattern, gitignore_file)
            for path in paths_to_check:
                if not spec.match_file(path):
                    yield path
        except GitWildMatchPatternError as e:
            print(f"Error {e} when parsing {gitignore_file}")
            yield from paths_to_check